package com.cainiao.aop;

import com.cainiao.mapper.LoginMapper;
import com.cainiao.pojo.Emp;
import com.cainiao.pojo.EmpLoginLog;
import com.cainiao.pojo.LoginInfo;
import com.cainiao.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LoginAspect {
    private String username;
    private String password;
    @Autowired
    private LoginMapper loginMapper;
    @Around("execution(* com.cainiao.controller.LoginController.login(*))")
    public Object loginCheck(ProceedingJoinPoint pjp)throws Throwable  {
        log.info("登录检查");
        Object[] args = pjp.getArgs();
        log.info("args:{}请求参数：", Arrays.toString(args));
        //判断args是否为空，并且是否为String类型
        Emp emp = (Emp)args[0];
        username = emp.getUsername();
        password = emp.getPassword();
        log.info("用户名：{}，密码：{}",username,password);
        LocalDateTime loginTime = LocalDateTime.now();
        log.info("登录时间：{}",loginTime);
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        log.info("执行结果为："+result);
        Result res = (Result) result;
        LoginInfo loginInfo = (LoginInfo)res.getData();
        log.info("loginInfo中的数据为"+loginInfo);
        long costTime = end - start;
        log.info("耗时：{}ms",costTime);
        log.info("登录结果：{}",result);
        Short isSuccess ;
        String jwt;
        if(loginInfo!=null){
            isSuccess = 1;
            jwt = loginInfo.getToken();
        }else{
            isSuccess = 0;
            jwt = null;
        }
        EmpLoginLog empLoginLog = new EmpLoginLog(null, username, password, loginTime, isSuccess, jwt, costTime);
        loginMapper.save(empLoginLog);
        log.info("登录日志：{}",empLoginLog);
        return result;
    }
}
